package com.myproject.jianghu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.myproject.jianghu.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
public class FileController {

    @Value("${filetype}")
    private String fileType;
    
    @Value("${rootPath}")
    private String rootPath;
    
    @Value("${filepath}")
    private String serverfilePath;

    @RequestMapping(value = "/file/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam("id") String blogId) {
        Result result=new Result();
        		
//    	String blogId=params.get("id");
    	if (file.isEmpty()) {
    		 result.setData(null);
             result.setMessage("failed");
             result.setStatusCode(300);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传后的路径
        String filePath = rootPath+"/"+serverfilePath+"/"+blogId+"//";
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.exists()) {
            dest.mkdirs();
        }
        File[] files = dest.listFiles();
        String number=new DecimalFormat("000").format(files.length+1);
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath+number + suffixName);
            System.err.println(path);

            Files.write(path, bytes);
            result.setData(serverfilePath+"/"+blogId+"/"+number+suffixName);
            result.setMessage("success");
            result.setStatusCode(200);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	        return result;
    }

    //文件下载相关代码
    @RequestMapping("/download/{vendId}")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable String vendId){
        String realPath =
                serverfilePath+vendId+"//";
        System.out.println("begin download");
        String fileName= getFilePath(realPath,vendId);
        if (fileName != null) {
            File file = new File(realPath+fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }

                    os.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }else {
            return "未上传相关附件";
        }
        return null;
    }
    //文件下载相关代码
    @RequestMapping("/file/download/{vendId}")
    @ResponseBody
    public String downloadZipFile(HttpServletRequest request, HttpServletResponse response,@PathVariable String vendId){
        String realPath =
                serverfilePath+vendId+"//";
        System.out.println("begin download");
        String fileName= getFilePath(realPath,vendId+fileType);
        if (fileName != null) {
            File file = new File(realPath+fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }

                    os.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }else {
            return "未上传相关附件";
        }
        return null;
    }

    //多文件上传
    @RequestMapping(value = "/file/batchupload", method = RequestMethod.POST)
    @ResponseBody
    public void handleFileUpload(HttpServletRequest request,@RequestParam("VEND_ID")String vendId) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("vendCertificate");
        String filePath = serverfilePath+vendId+"//";
        File dest = new File(filePath);
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            zipFile(files, vendId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void zipFile(List<MultipartFile> files,String vendId) throws IOException {
        File fileOut=new File(serverfilePath+vendId+"/"+vendId+fileType);//指定输出位置
        FileOutputStream fileOutputStream=new FileOutputStream(fileOut);//以流的形式输出
        ZipOutputStream zipOut=new ZipOutputStream(fileOutputStream);//注入到Zip中，以Zip的形式输出
        //在压缩文件中创建文件实体
        MultipartFile file = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            ZipEntry entry=new ZipEntry(file.getOriginalFilename());
            zipOut.putNextEntry(entry);
            byte[] bytes = file.getBytes();
            zipOut.write(bytes);
        }
        //将数组中的数据注入到ZipOutputStream中
        zipOut.closeEntry();
        zipOut.close();
        fileOutputStream.close();
    }



    private String getFilePath(String parentPath,String findName) {
        String path=null;

        File file = new File(parentPath);
        File[] files = file.listFiles();
        if(files==null||files.length<=0) {
            return path;
        }
        for (File child : files) {
            if (!child.isDirectory()) {
                String name=child.getName();
                if(name.contains(findName)) {
                    return name;
                }
            }
        }
        return path;
    }
}